package com.chen.tliaswebtest.service.impl;

import com.chen.tliaswebtest.exception.TliasException;
import com.chen.tliaswebtest.mapper.DeptMapper;
import com.chen.tliaswebtest.mapper.EmpMapper;
import com.chen.tliaswebtest.pojo.Dept;
import com.chen.tliaswebtest.service.DeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/24
 * 部门管理模块服务实现类
 */
@Service
// spring事务默认只回滚运行时异常，编译时异常不会回滚
// 指定属性rollbackFor = {Exception.class}，可以捕获所有异常进行回滚
@Transactional(rollbackFor = {Exception.class})
public class DeptServiceImpl implements DeptService {

    private final DeptMapper deptMapper;
    private final EmpMapper empMapper;

    public DeptServiceImpl(DeptMapper deptMapper, EmpMapper empMapper) {
        this.deptMapper = deptMapper;
        this.empMapper = empMapper;
    }

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    public void addDept(Dept dept) {
        if (deptMapper.list().stream().map(Dept::getName).anyMatch(s -> s.equals(dept.getName()))) {
            throw new TliasException("部门名称已存在!");
        }
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public void removeDeptById(Integer id) {
        if (empMapper.countByDeptId(id) > 0) {
            throw new TliasException("对不起，当前部门下有员工，不能直接删除！");
        }
        deptMapper.deleteDeptById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }

    @Override
    public Dept getDeptById(Integer id) {
        return deptMapper.selectById(id);
    }
}
